//
//  FKCacheTool.m
//  FKLibraryExample
//
//  Created by frank on 2018/8/13.
//  Copyright © 2018年 zmosa - frank. All rights reserved.
//

#import "FKCacheTool.h"
#import "JPUSHService.h"
#import "UserModel.h"


static NSString *const LoginInfo = @"loginInfo";
NSString * FKPath(NSString *path) {
    return  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:path];
}

@implementation FKCacheTool

+ (void)saveToken:(NSString *)token
{
    [kUserDefaults setObject:token forKey:@"token"];
    [kUserDefaults synchronize];
}

+ (NSString *)getToken
{
    return [kUserDefaults objectForKey:@"token"];
}

+ (BOOL)isLogin
{
    NSString *jsonStr = [kUserDefaults objectForKey:@"userInfo"];
    NSDictionary *userInfo = [jsonStr mj_JSONObject];
    return userInfo.count > 0;
}

+ (void)logout
{
    // 清空极光推送别名
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        NSLog(@"#########清空极光别名成功iResCode:(%zd), iAlias:(%@), seq:(%zd)", iResCode, iAlias, seq);
    } seq:1];
    
    [kUserDefaults removeObjectForKey:@"userInfo"];
    [kUserDefaults removeObjectForKey:@"contentVersion"];
    [kUserDefaults removeObjectForKey:@"onlineVersion"];
    [kUserDefaults removeObjectForKey:@"classInfo"];
}

+ (void)saveContentVersion:(NSString *)version
{
    if (!version) [kUserDefaults removeObjectForKey:@"contentVersion"];
    
    [kUserDefaults setObject:version forKey:@"contentVersion"];
    [kUserDefaults synchronize];
}

+ (NSString *)contentVersion
{
    return [kUserDefaults objectForKey:@"contentVersion"];
}

+ (BOOL)isHasUpdateOfContent
{
    // 每次启动，你拿到app时间戳和服务器上的对比, 如果没有修改/编辑/添加，那么时间戳一直是之前的时间
    NSString *contentVersion = [kUserDefaults objectForKey:@"contentVersion"];
    NSDate *serverVersionTime = [NSDate dateWithTimeIntervalSince1970:contentVersion.doubleValue];
    NSDate *currentTime = [NSDate date];
    if ([serverVersionTime compare:currentTime] == NSOrderedDescending) { //【代表有更新】
        return true;
    }
    return false;
}

+ (void)saveOnlineVersion:(NSString *)version
{
    if (!version) [kUserDefaults removeObjectForKey:@"onlineVersion"];
    
    [kUserDefaults setObject:version forKey:@"onlineVersion"];
    [kUserDefaults synchronize];
}

+ (NSString *)onlineVersion
{
    return [kUserDefaults objectForKey:@"onlineVersion"];
}

+ (void)saveUserInfo:(NSDictionary *)userInfo
{
    NSString *jsonStr = [userInfo mj_JSONString];
    [kUserDefaults setObject:jsonStr forKey:@"userInfo"];
    [kUserDefaults synchronize];
}

+ (UserModel *)userInfo
{
    NSString *jsonStr = [kUserDefaults objectForKey:@"userInfo"];
    NSDictionary *userInfo = [jsonStr mj_JSONObject];
    return [UserModel mj_objectWithKeyValues:userInfo];
//    return [kUserDefaults objectForKey:@"userInfo"];
}

+ (void)saveLastLoginName:(NSString *)loginName
{
    [kUserDefaults setObject:loginName forKey:@"lastLoginName"];
    [kUserDefaults synchronize];
}

+ (NSString *)lastLoginName
{
    return [kUserDefaults objectForKey:@"lastLoginName"];
}

+ (void)saveLastMobile:(NSString *)mobile
{
    [kUserDefaults setObject:mobile forKey:@"lastMobile"];
    [kUserDefaults synchronize];
}

+ (NSString *)lastMobile
{
    return [kUserDefaults objectForKey:@"lastMobile"];
}

+ (void)saveClassInfo:(NSDictionary *)classInfo
{
    if (classInfo) {
        NSString *jsonStr = [classInfo mj_JSONString];
        [kUserDefaults setObject:jsonStr forKey:@"classInfo"];
        [kUserDefaults synchronize];
    } else {
        [kUserDefaults removeObjectForKey:@"classInfo"];
    }
}

+ (NSDictionary *)classInfo
{
    NSString *jsonStr = [kUserDefaults objectForKey:@"classInfo"];
    return jsonStr ? [jsonStr mj_JSONObject] : nil;
}

+ (void)getCateData:(NSString *)cateId complete:(void (^)(id data))complete
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = cateId;
    NSString *fileName = fkFORMAT(@"/api/cateData_%@.json", cateId);
    if ([FKCacheTool isHasUpdateOfContent]) { // 有内容更新【直接请求】
        [SVProgressHUD show];
        [FKHttpTool getWithSuffix:@"/api/home/getCateData" param:param success:^(FKBaseResult *result) {
            [SVProgressHUD dismiss];
            if (result.isSuccess) {
                [self fk_setObject:result.data forPath:FKPath(fileName)];
                if (complete) complete(result.data);
            }
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
        }];
    } else {
        NSDictionary *data = [self fk_objectForPath:FKPath(fileName)];
        if (data) {
            if (complete) complete(data);
        } else {
            [SVProgressHUD show];
            [FKHttpTool getWithSuffix:@"/api/home/getCateData" param:param success:^(FKBaseResult *result) {
                [SVProgressHUD dismiss];
                if (result.isSuccess) {
                    [self fk_setObject:result.data forPath:FKPath(fileName)];
                    if (complete) complete(result.data);
                }
            } failure:^(NSError *error) {
                [SVProgressHUD dismiss];
            }];
        }
    }
}

+ (void)getIndexData:(NSString *)cateId complete:(void (^)(id data))complete
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = cateId;
    NSString *fileName = fkFORMAT(@"/api/indexData_%@.json", cateId);
    if ([FKCacheTool isHasUpdateOfContent]) { // 有内容更新【直接请求】
        [SVProgressHUD show];
        [FKHttpTool getWithSuffix:@"/api/home/getIndexData" param:param success:^(FKBaseResult *result) {
            [SVProgressHUD dismiss];
            if (result.isSuccess) {
                [self fk_setObject:result.data forPath:FKPath(fileName)];
                if (complete) complete(result.data);
            }
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
        }];
    } else { // 没有内容更新【先查缓存，缓存查不到再请求】
        NSDictionary *data = [self fk_objectForPath:FKPath(fileName)];
        if (data) {
            if (complete) complete(data);
        } else {
            [SVProgressHUD show];
            [FKHttpTool getWithSuffix:@"/api/home/getIndexData" param:param success:^(FKBaseResult *result) {
                [SVProgressHUD dismiss];
                if (result.isSuccess) {
                    [self fk_setObject:result.data forPath:FKPath(fileName)];
                    if (complete) complete(result.data);
                }
            } failure:^(NSError *error) {
                [SVProgressHUD dismiss];
            }];
        }
    }
}

+ (void)getCateList:(NSString *)cateId complete:(void (^)(id data))complete
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = cateId;
    NSString *fileName = fkFORMAT(@"/api/getCateList_%@.json", cateId);
    if ([FKCacheTool isHasUpdateOfContent]) { // 有内容更新【直接请求】
        [SVProgressHUD show];
        [FKHttpTool getWithSuffix:@"/api/home/getcatelist" param:param success:^(FKBaseResult *result) {
            [SVProgressHUD dismiss];
            if (result.isSuccess) {
                [self fk_setObject:result.data forPath:FKPath(fileName)];
                if (complete) complete(result.data);
            }
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
        }];
    } else { // 没有内容更新【先查缓存，缓存查不到再请求】
        NSDictionary *data = [self fk_objectForPath:FKPath(fileName)];
        if (data) {
            if (complete) complete(data);
        } else {
            [SVProgressHUD show];
            [FKHttpTool getWithSuffix:@"/api/home/getcatelist" param:param success:^(FKBaseResult *result) {
                [SVProgressHUD dismiss];
                if (result.isSuccess) {
                    [self fk_setObject:result.data forPath:FKPath(fileName)];
                    if (complete) complete(result.data);
                }
            } failure:^(NSError *error) {
                [SVProgressHUD dismiss];
            }];
        }
    }
}

+ (void)getMediaDetail:(NSString *)mediaId complete:(void (^)(id data))complete
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = mediaId;
    NSString *fileName = fkFORMAT(@"/api/home/getcatedetail_%@.json", mediaId);
    if ([FKCacheTool isHasUpdateOfContent]) { // 有内容更新【直接请求】
        [SVProgressHUD show];
        [FKHttpTool getWithSuffix:@"/api/home/getcatedetail" param:param success:^(FKBaseResult *result) {
            [SVProgressHUD dismiss];
            if (result.isSuccess) {
                [self fk_setObject:result.data forPath:FKPath(fileName)];
                if (complete) complete(result.data);
            }
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
        }];
    } else { // 没有内容更新【先查缓存，缓存查不到再请求】
        NSDictionary *data = [self fk_objectForPath:FKPath(fileName)];
        if (data) {
            if (complete) complete(data);
        } else {
            [SVProgressHUD show];
            [FKHttpTool getWithSuffix:@"/api/home/getcatedetail" param:param success:^(FKBaseResult *result) {
                [SVProgressHUD dismiss];
                if (result.isSuccess) {
                    [self fk_setObject:result.data forPath:FKPath(fileName)];
                    if (complete) complete(result.data);
                }
            } failure:^(NSError *error) {
                [SVProgressHUD dismiss];
            }];
        }
    }
}

+ (void)clearRequestData
{
    NSString *folderPath = FKPath(@"/api/");
    [self fk_cleanCacheDataWithCachPath:folderPath];
}


+ (void)setHistoryRecord:(BOOL)state;
{
    [kUserDefaults setBool:state forKey:@"HistoryRecord"];
    [kUserDefaults synchronize];
}

+ (BOOL)isOpenHistoryRecord
{
    return [kUserDefaults boolForKey:@"HistoryRecord"];
}

+ (void)setSearchRecord:(BOOL)state
{
    [kUserDefaults setBool:state forKey:@"SearchRecord"];
    [kUserDefaults synchronize];
}

+ (BOOL)isOpenSearchRecord
{
    return [kUserDefaults boolForKey:@"SearchRecord"];
}

+ (void)saveLastPlayVideo:(FKLastPlayMedia *)info
{
    NSString *jsonStr = [info mj_JSONString];
    [kUserDefaults setObject:jsonStr forKey:@"LastPlayVideo"];
    [kUserDefaults synchronize];
}

+ (void)removeLastPlayVideo
{
    [kUserDefaults removeObjectForKey:@"LastPlayVideo"];
}

+ (FKLastPlayMedia *)lastPlayVideo
{
    NSString *jsonStr = [kUserDefaults objectForKey:@"LastPlayVideo"];
    if (jsonStr) {
        NSDictionary *dict = [jsonStr mj_JSONObject];
        return [FKLastPlayMedia mj_objectWithKeyValues:dict];
    } else {
        return nil;
    }
}

#pragma mark - 文件缓存
+ (void)fk_setObject:(id)object forPath:(NSString *)path
{
    if (!object) {
        FKLog(@"SB，请不要传入空值好吗!");
        return;
    }
    
    if (![path isAbsolutePath]) {
        FKLog(@"---存储路径无效---");
        return;
    }
    
    NSData *cacheData = nil;
    if ([object isKindOfClass:[NSArray class]]) { // 如果传入的是模型数组
        NSArray *array = (NSArray *)object;
        if (array.count == 0) {
            FKLog(@"传入的数组元素个数为0");
            //            return;
            cacheData = [[NSData alloc] init];
        } else {
            id firstObj = array.firstObject;
            NSArray *keyValuesArray = [[firstObj class] mj_keyValuesArrayWithObjectArray:object];
            cacheData = [keyValuesArray mj_JSONData];
        }
    } else { // 如果传入的是模型对象或者dict
        cacheData = [object mj_JSONData];
    }
    
    // 如果路径中的文件夹不存在，则创建文件夹
    NSString *folderPath = [path stringByDeletingLastPathComponent];
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) {
        [manager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    // writeToFile:不会自动创建文件夹，所以路径中的文件夹都是必须存在的才能写入成功
    BOOL successful = [cacheData writeToFile:path atomically:true];
    
//    NSData *tempData = [NSData dataWithContentsOfFile:path];
//    NSDictionary*temp = [tempData mj_JSONObject];
    
    if (successful) {
        FKLog(@"--save success--");
    } else {
        FKLog(@"--save failure--");
    }
}

+ (void)fk_removeObjectForPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        BOOL removeSuccessful = [manager removeItemAtPath:path error:nil];
        if (removeSuccessful) {
            FKLog(@"---删除成功---");
        } else {
            FKLog(@"----删除失败----");
        }
    } else {
        FKLog(@"----文件不存在----");
    }
}

+ (id)fk_objectForPath:(NSString *)path
{
    NSData *cacheData = [NSData dataWithContentsOfFile:path];
    return [cacheData mj_JSONObject];
}


/*
 获取单个文件数据大小
 */
+ (long long)fk_fileSizeAtPath:(NSString *)filePath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    /* 不存在则返回0 */
    return 0;
}

/**
 获取整个缓存文件下的数据大小
 */
+ (float)fk_folderSizeAtPath:(NSString *)folderPath
{
    /* 创建文件管理者对象 */
    NSFileManager *manager = [NSFileManager defaultManager];
    /* 如果没有, 则返回0 */
    if (![manager fileExistsAtPath:folderPath]) return 0;

    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    /* 挨个遍历, 判断是否全部遍历 */
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        /* 逐个计算数据大小 */
        folderSize += [self fk_fileSizeAtPath:fileAbsolutePath];
    }
    /* 转换为字节返回 */
    return folderSize / (1024.0 * 1024.0);
}

/**
 清除缓存数据
 */
+ (void)fk_cleanCacheDataWithCachPath:(NSString *)cachPath
{
    /* 获取cachPath缓存文件夹中的数组文件 */
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    /* 遍历数组文件, 获取每个路径 */
    for (NSString *per in files) {
        NSError *error;
        /* 拼接路径 */
        NSString *path = [cachPath stringByAppendingPathComponent:per];
        /* 判断是否存在该文件路径, 存在就清除 */
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
}

@end
